<?php

namespace App\Models;

use Exception;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

/*总数字资源类型model*/

class ResourceSystemType extends BaseModel
{
    use HasFactory;

    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'change_time';


    protected $table = 'resource_system_type';



    /*关联书单书籍*/
    public function conResourceTotal()
    {
        return $this->belongsToMany(ResourceTotal::class, 'resource_total_type_intention', 'resource_guid', 'type_id', 'id', 'guid');
    }

    /**
     * 获取列表
     * @param limit int 分页大小
     * @param way string 籍获取方式 1、筛选书籍  2、选择书单 3、选择书商  4、每日荐书  5 、自定义封面并选择书籍
     * @param location int 显示位置 null 查询所有数据  0 全部(自适应)  1 图书  2 有声 3 视频 4 期刊 5 报纸 99 首页
     * @param keywords string 搜索关键词
     * @param is_play string 是否发布  1 发布 2 不发布
     */
    public function lists($search_data = [])
    {
        $keywords = $search_data['keywords'] ?? '';
        $way = $search_data['way'] ?? '';
        $location = $search_data['location'] ?? null;
        $is_play = $search_data['is_play'] ?? '';
        $limit = !empty($search_data['limit']) ? $search_data['limit'] : 10;
        $manage_resource_business_ids = request()->manage_info['resource_business_ids'] ?? [];

        $res = $this->from($this->getTable() . ' as r')
            ->select(['r.id', 'r.img', 'type_name', 'r.intro', 'r.way', 'r.is_play', 'r.sort', 'resource_business_id', 'resource_business_type_id', 'reading_id', 'read_id', 'r.template', 'r.create_time', 'r.location'])
            // ->join('resource_business_name as n', 'n.id', '=', 'r.resource_business_id')
            ->where(function ($query) use ($keywords) {
                if ($keywords) {
                    $query->where('type_name', 'like', "%$keywords%");
                }
            })->where(function ($query) use ($way, $is_play, $location) {
                if ($way) {
                    $query->where('way', $way);
                }
                if ($is_play) {
                    $query->where('is_play', $is_play);
                }
                if (is_numeric($location)) {
                    $query->where('location', $location);
                }
            })->where(function ($query) use ($manage_resource_business_ids) {
                if ($manage_resource_business_ids) {
                    $query->where('manage_id', request()->manage_id);
                }
            })
            ->where('r.is_del', 1)
            // ->where('n.is_del', 1)
            ->orderBy('sort')
            ->orderByDesc('id')
            ->paginate($limit)
            ->toArray();

        return $res;
    }

    /**
     * 详情
     * @param id int 系统类型id
     * @param is_play string 是否发布  1 发布 2 不发布
     */
    public function detail($id, $is_play = null)
    {
        $res = $this->select(['id', 'img', 'type_name', 'intro', 'way', 'is_play',  'sort', 'resource_business_id', 'resource_business_type_id', 'reading_id', 'read_id', 'template', 'location', 'create_time'])
            ->where(function ($query) use ($is_play) {
                if ($is_play) {
                    $query->where('is_play', $is_play);
                }
            })
            ->where('id', $id)
            ->where('is_del', 1)
            ->first();
        return $res;
    }


  /**
     *获取推荐的书单
     * @param way 书籍获取方式 1、筛选书籍  2、选择书单 3、选择书商  4、每日荐书  5 、自定义封面并选择书籍
     */
    public function getResourceSystemDataList($big_type_id = null, $limit = 10)
    {
        $res = $this->from($this->getTable() . ' as r')
            ->select('r.id', 'r.type_name', 'r.img', 'r.intro', 'way', 'resource_business_id', 'resource_business_type_id', 'reading_id', 'r.read_id', 'r.template', 'r.create_time')
            //->join('resource_business_name as n', 'n.id', '=', 'r.resource_business_id')
            ->where('r.is_del', 1)
            //  ->where('n.is_del', 1)
            ->where('r.is_play', 1)
            ->where(function ($query) use ($big_type_id) {
                if ($big_type_id) {
                    $query->orWhere('location', $big_type_id)->orWhere('location', 0);
                } else {
                    $query->orWhere('location', 99)->orWhere('location', 0);
                }
            })
            ->orderBy('r.sort')
            ->orderByDesc('id')
            ->limit($limit)
            ->get()
            ->toArray();
        $data = [];
        $i = 0;
        $resourceBusinessNameModel = new ResourceBusinessName();
        $resourceReadingListBookModel = new ResourceReadingListBook();
        $resourceReadRecomBookModel = new ResourceReadRecomBook();
        foreach ($res as $key => $val) {
            if ($val['way'] == 2) {
                //获取书单封面，重置img
                $img = ResourceReadingList::where('id', $val['reading_id'])->where('is_del', 1)->value('img');
                if (!$img) {
                    continue;
                }
                if ($big_type_id) {
                    //判断这个类型下是否有数据
                    $resource_total_count = $resourceReadingListBookModel->getResourceReadingListBookCount($val['reading_id'], $big_type_id);
                    if (empty($resource_total_count)) {
                        continue;
                    }
                }
                $data[$i]['img'] = $img;
            } elseif ($val['way'] == 4) {
                //获取书单封面，重置img
                // $img = ResourceReadRecom::where('id', $val['read_id'])->where('is_del', 1)->value('img');
                // if (!$img) {
                //     continue;
                // }
                if ($big_type_id) {
                    //判断这个类型下是否有数据
                    $resource_total_data = $resourceReadRecomBookModel->getResourceReadRecomBookId($val['read_id'], $big_type_id);
                    if (empty($resource_total_data)) {
                        continue;
                    }
                }

                $data[$i]['img'] = $val['img'];
            } elseif ($val['way'] == 1 || $val['way'] == 5) {
                if (empty($big_type_id)) {
                    if (in_array($val['template'], [1, 2, 3, 4, 5, 6, 7])) {
                        $big_type_ids = "1, 2, 4, 5";
                    } elseif (in_array($val['template'], [8])) {
                        $big_type_ids = 3;
                    }
                } else {
                    $big_type_ids = $big_type_id;
                }
                $resource_total_list = $this->getResourceSystemTypeDataListByTypeId($big_type_ids, $val['id'], null, 9);
                if (!$resource_total_list) {
                    continue;
                }
                //获取类型
                if ($val['way'] == 1) {
                    $resourceTypeExternalModel = new ResourceTypeExternal();
                    foreach ($resource_total_list as $k => $v) {
                        $resource_total_list[$k]['type_name'] = !empty($v['type_id']) ? $resourceTypeExternalModel->where('id', $v['type_id'])->where('is_del', 1)->value('type_name') : null;
                    }
                }
                $val['con_resource_total'] = $resource_total_list;
                $data[$i] = $val;
                $data[$i]['img'] = $val['img']; //1无封面，5有封面，所以可以一起赋值

                $big_type_ids = null; //重置掉
            } elseif ($val['way'] == 3) {
                if (empty($big_type_id)) {
                    if (in_array($val['template'], [1, 2, 3, 4, 5, 6, 7])) {
                        $big_type_ids = "1, 2, 4, 5";
                    } elseif (in_array($val['template'], [8])) {
                        $big_type_ids = 3;
                    }
                } else {
                    $big_type_ids = $big_type_id;
                }
                $resource_total_list = $resourceBusinessNameModel->getResourceBusinessDataByBusinessId(null, $val['resource_business_id'], $big_type_ids, $val['resource_business_type_id'], 1, 9);
                if (empty($resource_total_list['data'])) {
                    continue;
                }
                //获取类型
                $resourceTypeExternalModel = new ResourceTypeExternal();
                foreach ($resource_total_list['data'] as $k => $v) {
                    $resource_total_list['data'][$k]['type_name'] = !empty($v['type_id']) ? $resourceTypeExternalModel->where('id', $v['type_id'])->where('is_del', 1)->value('type_name') : null;
                }
                $val['con_resource_total'] = $resource_total_list['data'];
                $data[$i] = $val;
                $data[$i]['img'] = $val['img'];

                $big_type_ids = null; //重置掉
            } else {
                $data[$i]['img'] = $val['img'];
            }
            $data[$i]['id'] = $val['id'];
            $data[$i]['type_name'] = $val['type_name'];
            $data[$i]['intro'] = $val['intro'];
            $data[$i]['way'] = $val['way'];
            $data[$i]['reading_id'] = $val['reading_id'];
            $data[$i]['read_id'] = $val['read_id'];
            $data[$i]['template'] = $val['template'];
            $data[$i]['create_time'] = $val['create_time'];
            $i++;
        }
        return $data;
    }

    /**
     * 获取推荐的书单
     * @param type_id 系统类型id
     */
    public function getResourceSystemTypeDataListByTypeId($big_type_id = null, $type_id = null, $keywords = null, $limit = 10)
    {
        //获取敏感词
        // $sensitiveWordModel = new SensitiveWord();
        // $sensitive_word = $sensitiveWordModel->getSensitiveWordALL();

        $resourceTotalModel = new ResourceTotal();
        $resource_total_list = $resourceTotalModel->from('resource_total as r')
            ->select('r.guid', 'r.resource_business_id', 'r.title', 'r.author', 'r.press', 'r.pre_time', 'r.isbn', 'r.img', 'r.intro', 'r.type_id', 'r.big_type_id', 't.type_name as big_type_name', 'b.name as resource_business_name')
            ->join('resource_system_type_intention as i', 'r.id', '=', 'i.resource_id')
            ->join('resource_type as t', 't.id', '=', 'r.big_type_id')
            ->join('resource_business_name as b', 'b.id', '=', 'r.resource_business_id')
            ->where(function ($query) use ($big_type_id) {
                if ($big_type_id) {
                    $big_type_id = !is_array($big_type_id) ? explode(',', $big_type_id) : $big_type_id;
                    $query->whereIn('r.big_type_id', $big_type_id); //系统大类
                }
            })
            ->where(function ($query) use ($keywords) {
                if ($keywords) {
                    $query->where('r.title', 'like', '%' . $keywords . '%');
                }
            })
            ->where('is_mask', 1)
            ->where('r.is_del', 1)
            ->where('t.is_del', 1)
            ->where('b.is_del', 1)
            ->where('i.type_id', $type_id)
            ->orderByDesc('i.id')
            ->limit($limit)
            ->get()
            ->toArray();
        return $resource_total_list;
    }

    /**
     * 根据自定义类型获取资源列表
     * @param custom_type_id  自定义资源类型id  未传表示全部
     * @param keywords 关键字搜索
     * @param page 页数    默认第一页
     * @param limit 限制条数   默认 10 条
     */
    public function getCustomTypeResourceLists($keywords = null, $custom_type_id = null, $limit = 10)
    {
        //获取敏感词
        // $sensitiveWordModel = new SensitiveWord();
        // $sensitive_word = $sensitiveWordModel->getSensitiveWordALL();
        $resourceSystemTypeIntentionModel = new ResourceSystemTypeIntention();
        $res = $resourceSystemTypeIntentionModel->from($resourceSystemTypeIntentionModel->getTable() . ' as i')
            ->select([
                't.id',
                't.guid',
                't.resource_business_id',
                't.title',
                't.author',
                't.isbn',
                't.press',
                't.pre_time',
                't.img',
                't.intro',
                't.create_time',
                't.big_type_id',
                't.type_id',
                'to.type_name as big_type_name'
            ])
            ->join('resource_total as t', 't.id', '=', 'i.resource_id')
            ->join('resource_type as to', 'to.id', '=', 't.big_type_id')
            ->where(function ($query) use ($keywords) {
                if ($keywords) {
                    $query->where('title', 'like', "%$keywords%");
                }
            })
            ->where(function ($query) use ($custom_type_id) {
                if ($custom_type_id) {
                    $query->where('i.type_id', $custom_type_id);
                }
            })->where('is_mask', 1)
            ->where('t.is_del', 1)
            ->orderByDesc('i.id')
            ->paginate($limit)
            ->toArray();
        return $res;
    }
}
